/**
 * 分配角色
 */
import React, { useRef } from 'react';
import { Form } from 'antd';
import { useSetState, useMount } from 'ahooks';
import { default as EchoBox } from '../../../EchoBox';
import { getRoleList } from '@/services/power';
import { HttpCode } from '@/utils/contacts';

const FormItem = Form.Item;

const AssigningRoles = ({ form, roleListModel, echoRoles, defaultFlag }) => {
  const [state, setState] = useSetState({
    roleList: [],
  });
  const echoBoxRef = useRef(null);
  useMount(() => {
    _getRoleList();
  });

  const _getRoleList = async () => {
    echoBoxRef?.current?._changeLoading(true);
    const res = await getRoleList();
    echoBoxRef?.current?._changeLoading(false);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const data = [...(res?.data || [])];
      if (!defaultFlag) {
        data.forEach((item) => (item.saasAdminFlag = false));
      }
      setState({
        roleList: data,
      });
    } else {
      setState({
        roleList: [],
      });
    }
  };

  const handleEcho = (_list) => {
    echoRoles && echoRoles(_list);
  };
  return (
    <Form form={form} colon={false} requiredMark={false} labelAlign="left" layout={'vertical'}>
      <FormItem label="分配角色">
        <EchoBox
          ref={echoBoxRef}
          handleEcho={handleEcho}
          checkList={state.roleList}
          echoList={roleListModel}
          echoType="role"
          isRoles={true}
        />
      </FormItem>
    </Form>
  );
};

export default AssigningRoles;
